<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <header class="top-nav">
      <div class="logo">我的应用</div>
      <button class="logout-btn" @click="handleLogout">
        <i class="fa fa-sign-out"></i> 退出登录
      </button>
    </header>

    <div class="main-content">
      <!-- 侧边导航区 -->
      <aside class="sidebar">
        <button 
          class="nav-btn" 
          :class="{ active: activeSection === 'profile' }"
          @click="activeSection = 'profile'"
        >
          <i class="fa fa-user"></i> 个人信息
        </button>
        
        <!-- 我的订单按钮 - 所有身份都显示 -->
        <button 
          class="nav-btn" 
          :class="{ active: activeSection === 'orders' }"
          @click="goToOrdersPage"
        >
          <i class="fa fa-list-alt"></i> 我的订单
        </button>
        
        <!-- 身份对应功能入口 - 根据身份显示不同按钮 -->
        <button 
          class="role-entry-btn"
          @click="goToRolePage"
          v-if="userDetail.identity"
        >
          <i :class="roleIcon"></i> 
          {{ rolePageName }}
        </button>
      </aside>

      <!-- 应用区 -->
      <section class="app-area">
        <!-- 加载状态 -->
        <div v-if="isLoading" class="loading">
          <i class="fa fa-circle-o-notch fa-spin"></i> 加载中...
        </div>

        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-message">
          <i class="fa fa-exclamation-circle"></i> {{ errorMessage }}
          <button class="close-btn" @click="errorMessage = ''">
            <i class="fa fa-times"></i>
          </button>
        </div>

        <!-- 个人信息区域 -->
        <div v-if="activeSection === 'profile' && !isLoading && !errorMessage" class="profile-section">
          <h2 class="section-title">个人信息</h2>
          
          <div class="profile-card">
            <!-- 基本信息 -->
            <div class="profile-basic">
              <div class="avatar-container">
                <img 
                  :src="userDetail.image ? `/file${userDetail.image}` : defaultAvatar" 
                  alt="用户头像" 
                  class="avatar"
                >
                <label class="avatar-upload">
                  <input 
                    type="file" 
                    accept="image/jpeg, image/png" 
                    @change="handleAvatarUpload"
                    class="avatar-input"
                  >
                  <span class="upload-text">更换头像</span>
                </label>
              </div>
              
              <div class="basic-info">
                <p><strong>用户名：</strong>{{ userInfo.username }}</p>
                <p>
                  <strong>身份：</strong>
                  {{ identityMap[userDetail.identity] || '未设置' }}
                </p>
                <!-- 新增地址显示 -->
                <p><strong>地址：</strong>{{ userDetail.address || 'doro小区1号' }}</p>
              </div>
            </div>

            <!-- 详细信息表单 -->
            <form @submit.prevent="saveProfile" class="profile-form">
              <div class="form-row">
                <div class="form-group">
                  <label for="phone">手机号</label>
                  <input
                    type="tel"
                    id="phone"
                    v-model="userDetail.phone"
                    placeholder="请输入手机号"
                    class="form-input"
                    maxlength="11"
                  >
                </div>

                <div class="form-group">
                  <label for="sex">性别</label>
                  <select 
                    id="sex" 
                    v-model="userDetail.sex" 
                    class="form-select"
                  >
                    <option value="">请选择</option>
                    <option value="1">男</option>
                    <option value="2">女</option>
                  </select>
                </div>
              </div>

              <!-- 新增地址输入框 -->
              <div class="form-row">
                <div class="form-group">
                  <label for="address">地址</label>
                  <input
                    type="text"
                    id="address"
                    v-model="userDetail.address"
                    placeholder="请输入地址，默认：doro小区1号"
                    class="form-input"
                  >
                </div>
              </div>

              <!-- 保存按钮 -->
              <button 
                type="submit" 
                class="save-btn"
                :disabled="isSaving"
              >
                <span v-if="isSaving">保存中...</span>
                <span v-else><i class="fa fa-save"></i> 保存修改</span>
              </button>
              
              <!-- 保存成功提示 -->
              <div v-if="saveSuccess" class="success-message">
                <i class="fa fa-check-circle"></i> 信息保存成功
              </div>
            </form>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, toRefs, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

// 路由实例
const router = useRouter();

// 状态管理
const state = reactive({
  // 加载状态
  isLoading: true,
  isSaving: false,
  errorMessage: '',
  saveSuccess: false,
  
  // 活跃的区域
  activeSection: 'profile',
  
  // 用户信息
  userInfo: {}, // 基本信息
  userDetail: {}, // 详细信息
  
  // 身份映射
  identityMap: {
    '1': '商家',
    '2': '骑手',
    '3': '用户'
  },
  
  // 身份对应页面
  rolePageMap: {
    '1': 'StoreManage',  // 商家
    '2': 'Runner',       // 骑手
    '3': 'Consumer'      // 用户
  },
  
  // 身份对应页面名称 - 根据需求更新为不同显示文本
  rolePageNameMap: {
    '1': '店铺管理',
    '2': '骑手接单',
    '3': '美食天地'
  },
  
  // 身份对应图标
  roleIconMap: {
    '1': 'fa-shopping-bag',
    '2': 'fa-bicycle',
    '3': 'fa-cutlery'
  },
  
  // 默认头像
  defaultAvatar: 'https://picsum.photos/id/64/200/200',
  // 默认地址
  defaultAddress: 'doro小区1号(默认)'
});

const { 
  isLoading, isSaving, errorMessage, saveSuccess,
  activeSection, userInfo, userDetail, identityMap,
  rolePageMap, rolePageNameMap, roleIconMap, defaultAvatar,
  defaultAddress
} = toRefs(state);

// 计算属性：当前身份对应的页面名称
const rolePageName = computed(() => {
  return userDetail.value.identity 
    ? rolePageNameMap.value[userDetail.value.identity] 
    : '';
});

// 计算属性：当前身份对应的图标
const roleIcon = computed(() => {
  return userDetail.value.identity 
    ? `fa ${roleIconMap.value[userDetail.value.identity]}` 
    : 'fa-arrow-right';
});

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 获取基本信息
    const userRes = await axios.get('/user/user/now/');
    userInfo.value = userRes.data;
    
    // 获取详细信息
    const detailRes = await axios.put('/user/user/info/');
    userDetail.value = detailRes.data;
    
    // 如果地址为空，设置默认地址
    if (!userDetail.value.address) {
      userDetail.value.address = defaultAddress.value;
    }
  } catch (err) {
    errorMessage.value = err.response?.data?.message || '获取用户信息失败';
    console.error('获取用户信息失败:', err);
  } finally {
    isLoading.value = false;
  }
};

// 处理头像上传
const handleAvatarUpload = async (e) => {
  const file = e.target.files[0];
  if (!file) return;
  
  // 验证文件类型
  if (!['image/jpeg', 'image/png'].includes(file.type)) {
    errorMessage.value = '请上传JPG或PNG格式的图片';
    return;
  }
  
  isSaving.value = true;
  errorMessage.value = '';
  saveSuccess.value = false;
  
  try {
    const formData = new FormData();
    formData.append('file', file);
    
    // 更新头像
    const response = await axios.put('/user/user/info/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    // 更新头像显示
    userDetail.value.image = response.data.image;
    saveSuccess.value = true;
    setTimeout(() => saveSuccess.value = false, 3000);
  } catch (err) {
    errorMessage.value = err.response?.data?.message || '头像上传失败';
    console.error('头像上传失败:', err);
  } finally {
    isSaving.value = false;
    // 重置文件输入
    e.target.value = '';
  }
};

// 保存个人信息
const saveProfile = async () => {
  isSaving.value = true;
  errorMessage.value = '';
  saveSuccess.value = false;
  
  try {
    // 准备要提交的数据
    const formData = new FormData();
    if (userDetail.value.phone) formData.append('phone', userDetail.value.phone);
    if (userDetail.value.sex) formData.append('sex', userDetail.value.sex);
    if (userDetail.value.identity) formData.append('identity', userDetail.value.identity);
    // 新增地址提交（如果为空则提交默认地址）
    formData.append('address', userDetail.value.address || defaultAddress.value);
    
    // 更新个人信息
    const response = await axios.put('/user/user/info/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    // 更新本地数据
    userDetail.value = response.data;
    saveSuccess.value = true;
    setTimeout(() => saveSuccess.value = false, 3000);
  } catch (err) {
    errorMessage.value = err.response?.data?.message || '保存信息失败';
    console.error('保存信息失败:', err);
  } finally {
    isSaving.value = false;
  }
};

// 前往身份对应的功能页面
const goToRolePage = () => {
  if (userDetail.value.identity && rolePageMap.value[userDetail.value.identity]) {
    const pageName = rolePageMap.value[userDetail.value.identity];
    router.push(`/${pageName.toLowerCase()}`);
  }
};

// 前往订单页面
const goToOrdersPage = () => {
  activeSection.value = 'orders';
  router.push('/order');
};

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('token');
  router.push('/login');
};

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>


<style scoped>
/* 主容器样式 */
.home-container {
  min-height: 100vh;
  background-color: #fff;
  color: #333;
}

/* 顶部导航栏 */
.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 30px;
  background-color: #ff7a5a;
  color: white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
}

.logout-btn {
  background-color: white;
  color: #333;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s;
}

.logout-btn:hover {
  background-color: #f8f9fa;
  transform: translateY(-2px);
}

/* 主内容区 */
.main-content {
  display: flex;
  min-height: calc(100vh - 65px);
}

/* 侧边导航 */
.sidebar {
  width: 200px;
  background-color: #fff5f5;
  padding: 20px 0;
  border-right: 1px solid #ffe0e0;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.nav-btn {
  width: 100%;
  padding: 15px 20px;
  background: none;
  border: none;
  text-align: left;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s;
}

.nav-btn:hover {
  background-color: #ffe8e8;
}

.nav-btn.active {
  background-color: #ffd166;
  color: #333;
  font-weight: bold;
}

/* 身份对应功能入口按钮 */
.role-entry-btn {
  width: 100%;
  padding: 15px 20px;
  background-color: #ff7a5a;
  color: white;
  border: none;
  text-align: left;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 10px;
}

.role-entry-btn:hover {
  background-color: #e66a4c;
  transform: translateY(-2px);
}

/* 应用区 */
.app-area {
  flex: 1;
  padding: 30px;
  overflow-y: auto;
}

.section-title {
  color: #ff7a5a;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #ffd166;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 50px;
  color: #ff7a5a;
  font-size: 18px;
}

/* 错误提示 */
.error-message {
  background-color: #ffebee;
  color: #b71c1c;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.close-btn {
  background: none;
  border: none;
  color: #b71c1c;
  cursor: pointer;
  font-size: 16px;
}

/* 个人信息区域 */
.profile-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 0 15px rgba(255,122,90,0.1);
  padding: 25px;
}

.profile-basic {
  display: flex;
  align-items: center;
  gap: 30px;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f5f5f5;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #ffd166;
}

.avatar-upload {
  cursor: pointer;
}

.avatar-input {
  display: none;
}

.upload-text {
  color: #ff7a5a;
  font-weight: 500;
  text-decoration: underline;
}

.basic-info p {
  margin: 10px 0;
  font-size: 16px;
}

/* 表单样式 */
.profile-form {
  margin-top: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-group {
  flex: 1;
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #555;
  font-weight: 500;
}

.form-input, .form-select {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: #ff7a5a;
}

/* 保存按钮 */
.save-btn {
  background-color: #ffd166;
  color: #333;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.save-btn:hover {
  background-color: #ffc433;
  transform: translateY(-2px);
}

.save-btn:disabled {
  background-color: #ffeeba;
  cursor: not-allowed;
}

/* 成功提示 */
.success-message {
  margin-top: 15px;
  padding: 10px;
  background-color: #e8f5e9;
  color: #2e7d32;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #ffe0e0;
    flex-direction: row;
    overflow-x: auto;
  }
  
  .nav-btn, .role-entry-btn {
    justify-content: center;
    flex-shrink: 0;
  }
  
  .profile-basic {
    flex-direction: column;
    text-align: center;
  }
  
  .form-row {
    flex-direction: column;
    gap: 0;
  }
}
</style>